#include "script.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

lua_State* g_ufo_lua_state;

int ufoScriptRun(void* view, const char *script, void* wParam, void* lParam)
{
	if (!view || !script) {
		return 0;
	}

	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_loadstring(g_ufo_lua_state, script);
    
    *(void**)lua_newuserdata(g_ufo_lua_state,sizeof(void*)) = view;
    
    luaL_getmetatable(g_ufo_lua_state, "ufo.ufoView");
    lua_setmetatable(g_ufo_lua_state, -2);

	lua_pcall(g_ufo_lua_state, 1, 0, 0);

	return 1;
}

const char* internal_FiltUtf8BOM(const char* buf)
{
	if (buf[0] == -17 && buf[1] == -69 && buf[2] == -65)
		return buf + 3;

	return buf;
}

int ufoScriptAdd( const char* id, const char *script )
{
	lua_newtable(g_ufo_lua_state);
	lua_setglobal(g_ufo_lua_state, id);//"id" == "setting"
	
	lua_getglobal(g_ufo_lua_state, id);
	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setmetatable(g_ufo_lua_state, -2);
	lua_getfield(g_ufo_lua_state, LUA_GLOBALSINDEX, "_G");
	lua_setfield(g_ufo_lua_state, -2, "__index");
	
	luaL_loadstring(g_ufo_lua_state, internal_FiltUtf8BOM(script));//"script" == "function Init() ... end"
	lua_getglobal(g_ufo_lua_state, id);
	lua_setfenv(g_ufo_lua_state, -2);	

	lua_pcall(g_ufo_lua_state, 0, 0, 0);

	//### will call setting.Init()

	return 1;
}
